/**
 * @format
 * @Author: TC
 * @Date: 2025-04-26 08:51:08
 * @Last Modified by: TC
 * @Last Modified time: 2025-06-17 13:59:41
 */

import { _decorator, BlockInputEvents, instantiate, macro, Prefab, Sprite, tween } from "cc";
import { BaseComponent } from "db://assets/FrameWork/Module/Component/BaseComponent";
import { app } from "../../../FrameWork/App";
import { myGame } from "../../MyGame";
import { BaseUI } from "db://assets/FrameWork/Module/Component/BaseUI";
import { nsLoadingInterface } from "./Interface/LoadingInterface";
const { ccclass, property } = _decorator;

/**
 * 加载UI
 */
@ccclass("FullLoadingUI")
export class FullLoadingUI extends BaseUI {
    @property({ type: Sprite, displayName: "进度条" })
    spLoadingPro: Sprite = null;
    protected tasks: ((cb: Function) => void)[] = []; //预加载任务列表
    private _progress: number = 0; //当前进度
    private _maxProgress: number = 0; //最大进度
    private _simuateComplete: boolean = false;
    private _loadComplete: boolean = false;

    protected data: nsLoadingInterface.IFullLoadingUIData = null;
    protected init(): void {
        super.init();
        this.initPreloadTask();
        this._simulateLoading(0, 90);
        this._preload();
    }

    /**
     * 初始化预加载进度
     */
    protected initPreloadTask(): void {}

    /**
     * 初始化http请求地址
     */
    protected initHttpUrl(): void {}

    /**
     * 模拟进度条
     */
    private _simulateLoading(min: number, max: number): void {
        this._progress = min;
        this._maxProgress = max;
        this.schedule(this._onProgress, 0, macro.REPEAT_FOREVER, 0);
    }

    /**
     * 进度定时回调
     * @param dt
     */
    private _onProgress(dt: number): void {
        this.spLoadingPro.fillRange = this._progress / 100;
        if (this._progress >= this._maxProgress) {
            this._progress = this._maxProgress;
            this._simuateComplete = true;
            this.unschedule(this._onProgress);
            this._doCompleteCb();
        }
        this._progress += 1.5;
    }

    /**
     * 预加载资源
     */
    private _preload(): void {
        app.task.executeTaskList(this.data.taskList, () => {
            this._preloadComplete();
        });
    }

    /**
     * 预加载完成
     */
    private _preloadComplete(): void {
        this._loadComplete = true;
        this._doCompleteCb();
    }

    /**
     * 执行完成回调
     */
    private _doCompleteCb(): void {
        if (this._simuateComplete && this._loadComplete) {
            this.unschedule(this._onProgress);
            tween(this.spLoadingPro)
                .to(0.2, { fillRange: 1 })
                .call(() => {
                    if (this.data.completeCb) {
                        this.data.completeCb();
                    }
                    this.closeUI();
                })
                .start();
        }
    }
}
